#pragma once

#include <vector>
#include <thread>
#include <memory>
#include <condition_variable>
#include <queue>
#include <functional>



// 任务基类
/*
class Task {
public:
    virtual ~Task() = default;
    virtual void process() = 0;
};

*/  

// 前向声明
class ThreadPool;

// 任务队列
class TaskQueue {
public:
    //using ElemType = std::unique_ptr<Task>;
    using Task = std::function<void()>;
    using ElemType = std::unique_ptr<Task>;


    TaskQueue(size_t capacity);
    ~TaskQueue();

    void push(ElemType pTask);
    ElemType pop();
    bool full() const;
    bool empty() const;
    
    size_t get_waiting_tasks_count() const;
    
    void open();

    // 关闭队列
    void close();

    // 检查是否关闭
    bool is_closed() const {
        std::lock_guard<std::mutex> lock(m_mutex);
        return m_isClosed;
    }

private:
    size_t m_capacity;
    std::queue<ElemType> m_taskQueue;

    mutable std::mutex m_mutex;

    std::condition_variable m_notEmpty;
    std::condition_variable m_notFull;

    bool m_isClosed; // 队列是否关闭的标志
    friend class ThreadPool;
};


// 线程池类
class ThreadPool {
public:
    using Task = std::function<void()>;
    ThreadPool(size_t threadNum, size_t queueSize);
    ~ThreadPool();


    void start();
    void stop();

    // 立即关闭线程池并清空任务队列
    void shutdown_immediate();

    void addTask(std::unique_ptr<Task> pTask);                    

    size_t get_waiting_tasks_count() const {
        return m_taskQueue.get_waiting_tasks_count();
    }
    

private:
    // 工作线程调用的入口函数
    void woker_loop();

    size_t m_threadNum;
    std::vector<std::thread> m_threads;
    TaskQueue m_taskQueue;
    bool m_isExit;

    mutable std::mutex m_stateMutex;

};
